import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 商品状态类型
type ProductStatus = 'all' | 'active' | 'inactive' | 'pending';

// 商品接口
interface Product {
  id: string;
  name: string;
  price: number;
  category: string;
  status: 'active' | 'inactive' | 'pending';
  createdAt: string;
  seller: string;
  views: number;
  image: string;
}

// 模拟商品数据
const mockProducts: Product[] = [
  {
    id: '1',
    name: '九成新 MacBook Pro 2023',
    price: 8999,
    category: '电子产品',
    status: 'active',
    createdAt: '2023-10-30',
    seller: 'student1',
    views: 156,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=laptop%20macbook%20pro%20new%20condition&sign=20f4f73de7dc224e47978f4a391ca9b9'
  },
  {
    id: '2',
    name: '大学英语四级词汇书',
    price: 25,
    category: '书籍资料',
    status: 'active',
    createdAt: '2023-10-29',
    seller: 'student2',
    views: 89,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=english%20vocabulary%20book%20for%20exam&sign=69084fa9b4b4f62bc00931f403d1340b'
  },
  {
    id: '3',
    name: '专业相机 Canon EOS R5',
    price: 13500,
    category: '电子产品',
    status: 'pending',
    createdAt: '2023-10-28',
    seller: 'student3',
    views: 230,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=canon%20camera%20eos%20r5%20professional%20photography&sign=30344d19f8696fe1cf5b3eea840ba9d2'
  },
  {
    id: '4',
    name: '篮球装备套装',
    price: 199,
    category: '运动器材',
    status: 'active',
    createdAt: '2023-10-27',
    seller: 'student4',
    views: 120,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=basketball%20equipment%20set%20with%20ball%20and%20shoes&sign=c7c0864626ca8ad7c63c6063a27ea339'
  },
  {
    id: '5',
    name: '考研政治复习资料全套',
    price: 120,
    category: '书籍资料',
    status: 'inactive',
    createdAt: '2023-10-26',
    seller: 'student5',
    views: 98,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=postgraduate%20entrance%20exam%20political%20study%20materials&sign=ff90125a8a72b3ed5135015226dc85fb'
  },
  {
    id: '6',
    name: '小型咖啡机',
    price: 350,
    category: '家居用品',
    status: 'active',
    createdAt: '2023-10-25',
    seller: 'student6',
    views: 67,
    image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=small%20coffee%20machine%20home%20use&sign=f9436bb7c5cb7a23be2dbc7c6ed4c01d'
  }
];

// 分类列表
const categories = [
  { id: 'all', name: '全部分类' },
  { id: 'electronics', name: '电子产品' },
  { id: 'books', name: '书籍资料' },
  { id: 'sports', name: '运动器材' },
  { id: 'home', name: '家居用品' },
  { id: 'fashion', name: '服饰鞋包' },
  { id: 'other', name: '其他物品' }
];

export default function Products() {
  const [products, setProducts] = useState<Product[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
  const [selectedStatus, setSelectedStatus] = useState<ProductStatus>('all');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [isLoading, setIsLoading] = useState(true);
  const { theme } = useTheme();

  // 加载商品数据
  useEffect(() => {
    // 模拟API请求
    setTimeout(() => {
      setProducts(mockProducts);
      setFilteredProducts(mockProducts);
      setIsLoading(false);
    }, 1000);
  }, []);

  // 筛选商品
  useEffect(() => {
    let filtered = [...products];
    
    // 按状态筛选
    if (selectedStatus !== 'all') {
      filtered = filtered.filter(product => product.status === selectedStatus);
    }
    
    // 按分类筛选
    if (selectedCategory !== 'all') {
      const categoryMap: Record<string, string> = {
        'electronics': '电子产品',
        'books': '书籍资料',
        'sports': '运动器材',
        'home': '家居用品',
        'fashion': '服饰鞋包',
        'other': '其他物品'
      };
      
      filtered = filtered.filter(product => product.category === categoryMap[selectedCategory]);
    }
    
    // 按搜索关键词筛选
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(product => 
        product.name.toLowerCase().includes(query) || 
        product.category.toLowerCase().includes(query) ||
        product.seller.toLowerCase().includes(query)
      );
    }
    
    setFilteredProducts(filtered);
    setCurrentPage(1); // 重置到第一页
  }, [selectedStatus, selectedCategory, searchQuery, products]);

  // 计算分页
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredProducts.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(filteredProducts.length / itemsPerPage);

  // 改变商品状态
  const changeProductStatus = (productId: string, newStatus: 'active' | 'inactive') => {
    const updatedProducts = products.map(product => 
      product.id === productId ? { ...product, status: newStatus } : product
    );
    setProducts(updatedProducts);
    toast.success(`商品状态已更新为${newStatus === 'active' ? '上架' : '下架'}`);
  };

  // 审核商品
  const approveProduct = (productId: string) => {
    const updatedProducts = products.map(product => 
      product.id === productId ? { ...product, status: 'active' } : product
    );
    setProducts(updatedProducts);
    toast.success('商品已审核通过');
  };

  // 拒绝商品
  const rejectProduct = (productId: string) => {
    const updatedProducts = products.map(product => 
      product.id === productId ? { ...product, status: 'inactive' } : product
    );
    setProducts(updatedProducts);
    toast.success('商品已拒绝');
  };

  // 删除商品
  const deleteProduct = (productId: string) => {
    if (window.confirm('确定要删除该商品吗？此操作不可恢复。')) {
      const updatedProducts = products.filter(product => product.id !== productId);
      setProducts(updatedProducts);
      toast.success('商品已删除');
    }
  };

  // 状态样式映射
  const statusStyles = {
    'active': { text: '已上架', className: 'px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300' },
    'inactive': { text: '已下架', className: 'px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300' },
    'pending': { text: '待审核', className: 'px-2 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300' }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900")}>
      {/* 顶部导航 */}
      <header className="bg-white dark:bg-gray-800 shadow-sm sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center h-16">
            <div className="flex items-center">
              <Link to="/admin" className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 mr-4">
                <i className="fa-solid fa-arrow-left"></i>
              </Link>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">商品管理</h1>
            </div>
            
            <div className="flex items-center">
              <span className="text-sm text-gray-600 dark:text-gray-400 mr-4">欢迎，管理员</span>
              <div className="w-8 h-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
                <i className="fa-solid fa-user-shield text-gray-600 dark:text-gray-300"></i>
              </div>
            </div>
          </div>
        </div>
      </header>
      
      {/* 主体内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* 筛选和搜索 */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6 mb-6">
          <div className="flex flex-col md:flex-row gap-4">
            <div className="flex-1">
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <i className="fa-solid fa-search text-gray-400"></i>
                </div>
                <input
                  type="text"
                  placeholder="搜索商品名称、分类或卖家..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="block w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                />
              </div>
            </div>
            
            <div className="flex gap-4">
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                {categories.map(category => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
              
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value as ProductStatus)}
                className="block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="all">全部状态</option>
                <option value="active">已上架</option>
                <option value="inactive">已下架</option>
                <option value="pending">待审核</option>
              </select>
            </div>
          </div>
        </div>
        
        {/* 商品列表 */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden border border-gray-200 dark:border-gray-700">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-750">
                <tr>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    商品信息
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    分类
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    价格
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    卖家
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    发布时间
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    浏览量
                  </th>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    状态
                  </th>
                  <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                {currentItems.map((product) => (
                  <tr key={product.id} className="hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <div className="flex-shrink-0 h-12 w-12">
                          <img 
                            className="h-12 w-12 rounded-lg object-cover" 
                            src={product.image} 
                            alt={product.name}
                          />
                        </div>
                        <div className="ml-4">
                          <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {product.name}
                          </div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">
                            ID: {product.id}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-gray-100">{product.category}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                        ¥{product.price}
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="text-sm text-gray-900 dark:text-gray-100">{product.seller}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                      {product.createdAt}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                      {product.views}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={statusStyles[product.status].className}>
                        {statusStyles[product.status].text}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <div className="flex justify-end space-x-2">
                        <button
                          className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 dark:hover:text-indigo-300"
                        >
                          <i className="fa-solid fa-eye mr-1"></i>查看
                        </button>
                        
                        {product.status === 'pending' ? (
                          <>
                            <button
                              onClick={() => approveProduct(product.id)}
                              className="text-green-600 dark:text-green-400 hover:text-green-500 dark:hover:text-green-300"
                            >
                              <i className="fa-solid fa-check mr-1"></i>通过
                            </button>
                            <button
                              onClick={() => rejectProduct(product.id)}
                              className="text-red-600 dark:text-red-400 hover:text-red-500 dark:hover:text-red-300"
                            >
                              <i className="fa-solid fa-times mr-1"></i>拒绝
                            </button>
                          </>
                        ) : (
                          <>
                            <button
                              onClick={() => changeProductStatus(product.id, product.status === 'active' ? 'inactive' : 'active')}
                              className="text-blue-600 dark:text-blue-400 hover:text-blue-500 dark:hover:text-blue-300"
                            >
                              <i className={`fa-solid ${product.status === 'active' ? 'fa-pause' : 'fa-play'} mr-1`}></i>
                              {product.status === 'active' ? '下架' : '上架'}
                            </button>
                            <button
                              onClick={() => deleteProduct(product.id)}
                              className="text-red-600 dark:text-red-400 hover:text-red-500 dark:hover:text-red-300"
                            >
                              <i className="fa-solid fa-trash-can mr-1"></i>删除
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          
          {/* 分页 */}
          {filteredProducts.length > 0 && (
            <div className="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between">
              <div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
                <div>
                  <p className="text-sm text-gray-700 dark:text-gray-300">
                    显示 <span className="font-medium">{indexOfFirstItem + 1}</span> 到 <span className="font-medium">{Math.min(indexOfLastItem, filteredProducts.length)}</span> 条，共 <span className="font-medium">{filteredProducts.length}</span> 条记录
                  </p>
                </div>
                <div>
                  <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                    <button
                      onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                      disabled={currentPage === 1}
                      className={`relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${
                        currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      <span className="sr-only">上一页</span>
                      <i className="fa-solid fa-chevron-left text-xs"></i>
                    </button>
                    
                    {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                      // 简单的分页逻辑，显示当前页附近的页码
                      let pageNum;
                      if (totalPages <= 5) {
                        pageNum = i + 1;
                      } else if (currentPage <= 3) {
                        pageNum = i + 1;
                      } else if (currentPage >= totalPages - 2) {
                        pageNum = totalPages - 4 + i;
                      } else {
                        pageNum = currentPage - 2 + i;
                      }
                      
                      return (
                        <button
                          key={pageNum}
                          onClick={() => setCurrentPage(pageNum)}
                          className={`relative inline-flex items-center px-4 py-2 border ${
                            currentPage === pageNum
                              ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-300 dark:border-indigo-700 text-indigo-700 dark:text-indigo-300'
                              : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                          } text-sm font-medium`}
                        >
                          {pageNum}
                        </button>
                      );
                    })}
                    
                    <button
                      onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                      disabled={currentPage === totalPages}
                      className={`relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${
                        currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''
                      }`}
                    >
                      <span className="sr-only">下一页</span>
                      <i className="fa-solid fa-chevron-right text-xs"></i>
                    </button>
                  </nav>
                </div>
              </div>
              
              {/* 移动端分页 */}
              <div className="flex items-center justify-between w-full sm:hidden">
                <p className="text-sm text-gray-700 dark:text-gray-300">
                  共 {filteredProducts.length} 条记录
                </p>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                    disabled={currentPage === 1}
                    className={`px-3 py-1 border rounded text-sm ${
                      currentPage === 1
                        ? 'border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                        : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                    }`}
                  >
                    上一页
                  </button>
                  <button
                    onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
                    disabled={currentPage === totalPages}
                    className={`px-3 py-1 border rounded text-sm ${
                      currentPage === totalPages
                        ? 'border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed'
                        : 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                    }`}
                  >
                    下一页
                  </button>
                </div>
              </div>
            </div>
          )}
          
          {/* 空状态 */}
          {filteredProducts.length === 0 && (
            <div className="px-6 py-12 text-center">
              <div className="inline-flex items-center justify-center p-6 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
                <i className="fa-solid fa-box-open text-3xl text-gray-400"></i>
              </div>
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">暂无商品数据</h3>
              <p className="text-gray-500 dark:text-gray-400">
                当前筛选条件下没有找到符合的商品
              </p>
              <button
                onClick={() => {
                  setSelectedStatus('all');
                  setSelectedCategory('all');
                  setSearchQuery('');
                }}
                className="mt-4 px-4 py-2 rounded-lg text-sm font-medium bg-indigo-600 dark:bg-indigo-500 text-white hover:bg-indigo-700 dark:hover:bg-indigo-600"
              >
                重置筛选条件
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}